#!/usr/bin/env python

import datetime

class SM2:
    
    def __init__(self):
        self.easiness_factor = 2.5
        self.number_repetitions = 0
        self.quality_of_last_recall = None
        self.repetition_interval = None
        self.next_repetition = None
        self.last_studied = None
        
    def process_recall_result(self, quality_of_recall):
        assert quality_of_recall >= 0
        assert quality_of_recall <= 5
        assert self.easiness_factor
        
        if quality_of_recall < 3:
            self.number_repetitions = 0
            self.repetition_interval = 0
        else:
            self.easiness_factor = self._calculate_easiness_factor(self.easiness_factor, quality_of_recall)
            
            if quality_of_recall == 3:
                self.repetition_interval = 0
            else:
                self.number_repetitions += 1
                
                if self.number_repetitions == 1:
                    self.repetition_interval = 1
                elif self.number_repetitions == 2:
                    self.repetition_interval = 6
                else:
                    self.repetition_interval = self.repetition_interval * self.easiness_factor
                    
        self.next_repetition = datetime.date.today() + datetime.timedelta(days=self.repetition_interval)
        self.last_studied = datetime.date.today()        
    
    def is_scheduled_to_recall(self):
        return self.next_repetition and self.next_repetition <= datetime.date.today()
    
    def _calculate_easiness_factor(self, ef, q):
        result = ef - 0.8 + (0.28*q) - (0.02*q*q)
        
        if result < 1.3: result = 1.3
            
        return result
    
    
if __name__ == '__main__':
    sm2 = SM2()
    sm2.process_recall_result(5)
    print sm2.next_repetition